package server

import (
	"fmt"
	"net"
	"time"

	"gitee.com/gtsoa/bsdemo/bsdemopb"
	"gitee.com/gtsoa/bsdemo/models"
	"gitee.com/gtsoa/mspkg/config"
	//"gitee.com/gtsoa/mspkg/dsclients"
	"github.com/grpc-ecosystem/go-grpc-middleware"
	grpc_logrus "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus"
	grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
	"github.com/sirupsen/logrus"
	"google.golang.org/grpc"
)

type Server struct {
	DemoService

	cfg     *config.ServerConfig
	demoCfg *models.Config
}

func newServer() *Server {
	svr := new(Server)
	svr.cfg = config.ParseServerConfig()
	svr.demoCfg = models.ParseConfig()

	svr.DemoService.init()

	return svr
}

func Main() {
	server := newServer()

	// log middleware
	logrusEntry := logrus.NewEntry(logrus.StandardLogger())
	logrusOpts := []grpc_logrus.Option{
		grpc_logrus.WithDurationField(func(duration time.Duration) (key string, value interface{}) {
			return "grpc.time_ns", duration.Nanoseconds()
		}),
	}

	svc := grpc.NewServer(
		grpc_middleware.WithUnaryServerChain(
			grpc_logrus.UnaryServerInterceptor(logrusEntry, logrusOpts...),
			grpc_recovery.UnaryServerInterceptor(),
			AuthUnaryIntercepter(false),
		),
		grpc_middleware.WithStreamServerChain(
			grpc_logrus.StreamServerInterceptor(logrusEntry, logrusOpts...),
			grpc_recovery.StreamServerInterceptor(),
		),
	)
	bsdemopb.RegisterSServer(svc, server)
	listen, err := net.Listen("tcp", fmt.Sprintf("%v:%d", server.cfg.Address, server.cfg.Port))
	if err != nil {
		logrus.Fatalf("Listen error: %v", err)
	}
	logrus.Infof("Server Listen at %v:%d", server.cfg.Address, server.cfg.Port)
	svc.Serve(listen)
	logrus.Infof("Terminated Server at %v", time.Now().Local())
}
